package com.yanghui.filter;

import com.yanghui.pojo.BlackIp;
import com.yanghui.service.BlackIpService;
import com.yanghui.utils.UserIpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 配置 Filter，禁止黑名单上的 IP地址 进行访问
 */
public class IpFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        /** 获取到用户的 IP 地址 */
        String ip = UserIpUtil.getIp(req);

        HttpSession session = req.getSession();
        ServletContext servletContext = session.getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        BlackIpService blackIpService = applicationContext.getBean(BlackIpService.class);

        /** 去黑名单数据表中查询是否存在 */
        List<BlackIp> blackIpList = blackIpService.selectByIp(ip);

        /** 如果不存在，则放行 */
        if (blackIpList.size() == 0) {
            chain.doFilter(req, resp);
        /** 否则请求转发到错误页面 */
        } else {
            request.getRequestDispatcher("/errorPage/blackIp.jsp").forward(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
